package cc.itez.wx.linkman.service.impl;

import cc.itez.wx.linkman.mould.WxReply;
import cc.itez.wx.linkman.service.MessageSender;
import cc.itez.wx.linkman.config.WxProfile;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.StringWriter;

@Log4j2
@Service
public class MessageSenderImpl implements MessageSender {
    @Autowired
    WxProfile profile;

    @Override
    public String replyText(String openId, String text) {
        try {
            WxReply reply = new WxReply().setMsgType("text").setContent(text)
                .setFromUserName(profile.getWxId()).setToUserName(openId);
            JAXBContext context = JAXBContext.newInstance(WxReply.class);
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            StringWriter writer = new StringWriter();
            marshaller.marshal(reply, writer);
            return writer.toString();
        } catch (JAXBException e) {
            log.error(e);
        }
        return "";
    }
}
